package com.example.demo.util;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DatabaseInitializer {
    private static final String DB_PATH = "data/one-agent.db";
    private static final String INIT_SCRIPT = "src/main/resources/scripts/init.sql";
    private static final String INIT_DATA_SCRIPT = "src/main/resources/scripts/init_data.sql";

    public static void initializeDatabase() {
        File dbFile = new File(DB_PATH);
        if (!dbFile.exists()) {
            try {
                // 创建data目录
                Files.createDirectories(Paths.get("data"));
                
                // 连接SQLite数据库
                Connection connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
                Statement statement = connection.createStatement();
                
                // 执行初始化脚本
                String initSql = new String(Files.readAllBytes(Paths.get(INIT_SCRIPT)));
                statement.executeUpdate(initSql);
                
                // 执行初始化数据脚本
                String initDataSql = new String(Files.readAllBytes(Paths.get(INIT_DATA_SCRIPT)));
                statement.executeUpdate(initDataSql);
                
                statement.close();
                connection.close();
                
                System.out.println("数据库初始化完成");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}